package com.ruoyi.sqldow.service.impl;


import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 备份sql文件
 */
@Service
public class BackUpServiceImpl {
    public String BackUps(){
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date date= new Date();
        //
        // 指定导出的 sql 存放的文件夹
        //
        String sqlPath="/GrowseedMS/sqldowload/";
//        String sqlPath="D:/a/";


        File saveFile = new File(sqlPath);
        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }
        String host = "127.0.0.1";

        String userName="root";
        //密码
        String password = "hzau123";
        //要保存数据库名
        String dataBaseName = "zmgs";
        //
        String fileName = f.format(date) + ".sql";
        System.out.println(fileName);
        StringBuilder sb = new StringBuilder();
        // 拼接备份命令
        sb.append("/usr/bin/mysqldump").append(" --opt").append(" -h ").append(host).append(" --user=").append(userName).append(" --password=").append(password);
        sb.append(" --result-file=").append(sqlPath + fileName).append(" --default-character-set=utf8 ").append(dataBaseName);
        System.out.println(sb);
        try {
            Process exec = Runtime.getRuntime().exec(sb.toString());
            if (exec.waitFor() == 0) {
                System.out.println("数据库备份成功，保存路径：" + sqlPath);
            } else {
                System.out.println("process.waitFor()=" + exec.waitFor());
            }
        } catch (IOException e) {
        } catch (InterruptedException e) {
        } catch (Exception e) {
        }
        return sqlPath+fileName;
    }
}


